#include "CppProjectGameModeBase.h"
#include "Framework/Application/SlateApplication.h"
#include "./ThirdParty/include/ProcessManagerInterface.h"
#include "StatusSetting.h"
#include <Kismet/GameplayStatics.h>

void ACppProjectGameModeBase::StartPlay()
{
	Super::StartPlay();

	DWORD CreateResult;
#if WITH_EDITOR
	FString ParentDir = FPaths::GetPath(FPaths::ProjectDir());
	int32 LastSlashIndex;
	ParentDir.FindLastChar('/', LastSlashIndex);
	ParentDir.LeftInline(LastSlashIndex);

	FString CustomPath = TEXT("UI_Simulator/x64/Debug/UI_Monitor.exe");
	FString CombinedPath = FPaths::Combine(ParentDir, CustomPath);
	FString ApplicationPath = CombinedPath.Replace(TEXT("/"), TEXT("\\"));
	CreateResult = ProcessManager::CProcessManagerInterface::getOrCreateProcess(*ApplicationPath);
#else
	UStatusSettingConfig::LoadIniFile();
	static FString TitleName = "MonitorTool";
	FString ApplicationPath = UStatusSettingConfig::ReadFString(*TitleName, TEXT("ApplicationPath"));
	FString ProcessName = UStatusSettingConfig::ReadFString(*TitleName, TEXT("ProcessName"));
	FString CrashPath = UStatusSettingConfig::ReadFString(*TitleName, TEXT("CrashPath"));
	FString Commandline = ProcessName + " " + CrashPath;
	CreateResult = ProcessManager::CProcessManagerInterface::getOrCreateProcess(*ApplicationPath, *Commandline);
#endif

	FWindowsApplication* pApplication = static_cast<FWindowsApplication*>(FSlateApplication::Get().GetPlatformApplication().Get());
	check(pApplication);
	pApplication->AddMessageHandler(m_UIMessager);

	HWND m_HwndReceiver = NULL;
	auto start = clock();
	while (m_HwndReceiver == NULL)
	{
		m_HwndReceiver = FindWindowW(L"MonitorWindowClass", L"MonitorWindow");
		auto end = clock();
		if (double(end - start) / CLOCKS_PER_SEC >= 10.0)
		{
			UE_LOG(UIMessager, Warning, TEXT("Monitor window does not exist, recording will be canceled."));
			break;
		}
	}

	APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0);
	m_UIMessager.sendStartMessage(PlayerController);
}

void ACppProjectGameModeBase::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	Super::EndPlay(EndPlayReason);

	FWindowsApplication* pApplication = static_cast<FWindowsApplication*>(FSlateApplication::Get().GetPlatformApplication().Get());
	check(pApplication);
	pApplication->RemoveMessageHandler(m_UIMessager);
	m_UIMessager.sendEndMessage();
}